﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OnlineStore.Bll;
using System.Data.Linq;

namespace OnlineStore.Dal
{
    public class DalOrder
    {
        OnlineStoreDataContext data = new OnlineStoreDataContext();
        public DalOrder() { }
        public bool addOrder(List<bizCart> listCart, tbCustomer User)
        {
            try
            {
                DalProduct _dalProduct = new DalProduct();
                tbOrder _order = new tbOrder();
                _order.Order_Id = Max + 1;
                _order.Customer_ID = User.Cus_ID;
                _order.Status = "Waiting";
                _order.Created_Date = DateTime.Now;
                data.tbOrders.InsertOnSubmit(_order);
                data.SubmitChanges();
                double Total = 0;
                foreach (bizCart i in listCart)
                {
                    Total += i.Sum;
                    _dalProduct.UpdateOrder(i);
                    tbOrderDetail _orderDetail = new tbOrderDetail();
                    _orderDetail.Order_ID = _order.Order_Id;
                    _orderDetail.Product_ID = i.ID;
                    _orderDetail.Price = i.Price;
                    _orderDetail.Qty = i.NumberOrder;
                    data.tbOrderDetails.InsertOnSubmit(_orderDetail);
                    if(i.NumberOrder > i.Stock)
                        _order.Status = "Waiting for Approve";
                }
                _order.Total = (int)Total;
                data.SubmitChanges();
                return true;
            }
            catch(ChangeConflictException)
            {
                data.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
                data.SubmitChanges();
                return false;
            }
            
        }
        public static int Max
        {
            get
            {
                OnlineStoreDataContext data = new OnlineStoreDataContext();
                var list = (from p in data.tbOrders
                       select p.Order_Id).ToList();
                if (list.Count== 0 ) return 0;

                return list.Max();
            }

        }
    
    }
}